package com.yuchuang.controller;

import com.yuchuang.base.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/**
 * @Author:cy Date: 2023-06-20-14:00
 * Description:
 *
 @Value("${env.config}")   //获取application 的配置环境信息
 private String prod;
// Arrays.toString()以数组的形式输出
 */
@RestController
@RequestMapping("/upload")
@Api(tags="上传图片")
public class uploadController {
    @Value("${env.config}")
    private String prod;
    @PostMapping("/image")
    public Result image(MultipartFile file){
        System.out.println("配置环境"+prod);
        //file校验
        if(file.isEmpty()){
            return Result.fail("上传失败");
        }
        //file  图片重命名
        String originalFilename = file.getOriginalFilename();//原来的图片名称
        String ext = "."+originalFilename.split("\\.")[1];//获取后缀
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = uuid + ext;
        String pre;

        System.out.println("判断环境是否执行"+prod.equals("pro"));
        System.out.println(Arrays.toString(prod.getBytes()));
        System.out.println(Arrays.toString("pro".getBytes()));
        if(prod.equals("pro")){
            System.out.println("获取上传位置=======");
            //线上环境
            //上传图片  到linux  /usr/local/nginx/html/home/files/images
            String uploadUrl = "/home/files/images";
            // 获取上传的位置（存放图片的文件夹）,如果不存在，创建文件夹
            File fileParent = new File(uploadUrl);
            System.out.println("fileParent======="+fileParent);
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            System.out.println("pre=======");
            pre = "/home/files/images/";
            System.out.println("pre=====prepre=="+pre);


        }else{
            //本地环境
            //上传图片  到本地   访问本地图片路径  需要配置MyMvcConfig    image/**
            ApplicationHome applicationHome = new ApplicationHome(this.getClass());
             pre = applicationHome.getDir().getParentFile().getParentFile().getAbsoluteFile() +
                    "\\src\\main\\resources\\static\\images\\";
        }

        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.ok("上传成功",fileName);
    }
}
